package pt.isec.a21210392.a21190220.ludotwist;

import java.io.ObjectInputStream;
import java.net.InetAddress;
import java.net.Socket;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class JoinGameActivity extends Activity 
{
	public static Socket socket;
	public static ObjectInputStream in;
	private EditText hostIP;	
	private TextView information;
	private Button button;
	private boolean started = false;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) 
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_join_game);
		hostIP = (EditText)findViewById(R.id.jg_ip);
		information = (TextView)findViewById(R.id.information);
		button = (Button)findViewById(R.id.jg_joingame);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) 
	{
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.join_game, menu);
		return true;
	}
	
	public void onJoinGame(View v)
	{
		new JoinThread().start();
		button.setEnabled(false);
	}
	
	class JoinThread extends Thread
	{
		private String ip;
		
		public void runOnUI(String message)
		{
			final String finalMessage = message;
			
			runOnUiThread(new Runnable() 
			{				
				@Override
				public void run() 
				{
					information.setText(information.getText() + "\n" + finalMessage);
				}
			});
		}
		@Override
		public void run() 
		{
			ip = hostIP.getText().toString();
			try
			{			
				runOnUI(R.string.jg_connecting + ip);
				socket = new Socket(InetAddress.getByName(ip),Constants.PORT);
				runOnUI("\n" + R.string.jg_connected);

				in = new ObjectInputStream(socket.getInputStream());				
				runOnUI("\n\n" + R.string.jg_waiting);
				
				Message message = (Message)in.readObject();
				
				if(message.getMessage().equals(Constants.START))
				{
					final int number = (Integer)message.getObject();
					runOnUiThread(new Runnable() 
					{			
						@Override
						public void run() 
						{
							Intent myIntent = new Intent(JoinGameActivity.this, GameActivity.class);
							myIntent.putExtra("fromJoin", true);
							myIntent.putExtra("number", number);
							JoinGameActivity.this.startActivity(myIntent);
							started = true;
						}
					});
				}
				while(!started){}
			}
			catch(Exception e){}
		}
	}
}
